<route>
  {
      meta: {
          layout: 'index',
          title:'角色管理'
      }
  }  
</route>
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <DeptSelectTree @confirm="deptConfirm"></DeptSelectTree>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="角色标识" prop="roleKey">
            <el-input v-model="queryParams.roleKey" placeholder="请输入角色标识" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 240px">
              <el-option v-for="dict in status_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain :icon="Plus" @click="handleAdd"
              v-hasPermi="['system:role:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain :icon="Edit" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:role:update']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:role:delete']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="doQuery()"></right-toolbar>
        </el-row>
        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="角色编号" prop="id" width="120" align="center" />
          <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
          <el-table-column label="角色标识" prop="roleKey" :show-overflow-tooltip="true" width="100" />
          <el-table-column label="角色描述" prop="roleDescription" :show-overflow-tooltip="true" width="150" />
          <el-table-column label="显示顺序" prop="roleSort" width="100" />
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.roleId !== 1">
                <el-button type="text" :icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:role:update']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.roleId !== 1">
                <el-button type="text" :icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:role:delete']"></el-button>
              </el-tooltip>
              <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
                <el-button type="text" :icon="User" @click="handleAuthUser(scope.row)"
                  v-hasPermi="['system:privilege:grant']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="180" align="center" prop="createdTime">
            <template #default="scope">
              <span>{{ scope.row.createdTime }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="doQuery()" />
      </el-col>
    </el-row>
    <!-- 新增&修改表单 -->
    <AntdConfirmModal :title="isCreate ? '新建角色' : '更新角色'" ref="modalRef" :keepSlot="false" @confirm="submitTypeForm">
      <a-form :model="form" name="basic" :label-col="{ span: 6 }">
        <a-form-item label="归属部门" name="deptId" label-width="100px" :rules="[{ required: true, message: '选择归属部门' }]">
          <a-tree-select v-model:value="form.deptId" allow-clear :tree-data="deptStore.deptTree" :field-names="{
            value: 'id',
            label: 'deptName',
            children: 'children',
          }" placeholder="选择归属部门" />
        </a-form-item>
        <a-form-item label="角色名称" name="roleName" :rules="[{ required: true, message: '请输入角色名称' }]">
          <a-input v-model:value="form.roleName" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item label="权限字符" name="roleKey" :rules="[{ required: true, message: '请输入权限字符' }]">
          <a-input v-model:value="form.roleKey" placeholder="请输入权限字符" />
        </a-form-item>
        <a-form-item label="角色顺序" name="roleSort">
          <a-input-number v-model:value="form.roleSort" :min="0" style="width: 150px" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="form.status">
            <a-radio v-for="dict in status_dict" :value="dict.value" :key="dict.value" :label="dict.value">{{
              dict.label
            }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="资源权限">
          <a-tree-select v-model:value="form.permissions" tree-checkable allow-clear :tree-data="resOptions"
            placeholder="选择资源权限" :field-names="{
              value: 'label',
              label: 'label',
              children: 'children',
            }" />
        </a-form-item>
        <a-form-item label="角色描述" name="roleDescription">
          <a-textarea v-model:value="form.roleDescription" type="textarea" placeholder="请输入内容"></a-textarea>
        </a-form-item>
      </a-form>
    </AntdConfirmModal>
    <!--授权弹窗-->
    <AntdShowModal :title="`【` + selectedRole?.roleName + '-' + selectedRole?.roleKey + `】用户管理`" :width="880"
      ref="userGrantRef">
      <UserGrantManager :roleId="selectedRole.id" />
    </AntdShowModal>
  </div>
</template>

<script setup>
import DeptSelectTree from "../../components/DeptSelectTree";
import UserGrantManager from '../../components/UserGrantManager';
import { Delete, Edit, Plus, Search, Refresh, User } from "@element-plus/icons-vue";
import { createOne, deleteOne, queryOne, queryList, updateOne } from "../../api/role";
import { treeSelect as resTree } from "../../api/res";
import { status_dict } from "@/constant/dict";
import useApp from "@/hooks";
import useDeptStore from "../../store/dept";
const deptStore = useDeptStore();
const { $, proxy } = useApp();
const tableData = ref()
const modalRef = ref(null);
const isCreate = ref(true);
const router = useRouter();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const resOptions = ref([]);
const checkedKeys = ref([]);
const selectedRole = ref(null)
const userGrantRef = ref(null)
const queryParams = ref({
  deptId: undefined,
  pageNum: 1,
  pageSize: 10,
  roleName: undefined,
  roleKey: undefined,
  status: undefined,
  sortBy: "roleSort",
  order: "AES",
})
const form = ref({
  deptId: undefined,
  id: undefined,
  permissions: [],
  roleDescription: undefined,
  roleKey: undefined,
  roleName: undefined,
  roleSort: 0,
  status: 1,
});
//增
function handleAdd() {
  reset();
  getResTree();
  checkedKeys.value = [];
  isCreate.value = true;
  openModal();
  title.value = "添加角色";
}
// 删
function handleDelete(row) {
  const roleIds = row.id ? [row.id] : ids.value;
  $.showModal({
    title: '确认提醒',
    type: 'warning',
    content: `是否删除${row.roleName}`,
    cancelText: '取消'
  }).then(r => {
    if (r.confirm) {
      roleIds.forEach(function (ele) {
        deleteOne(ele).then(res => {
          $.showToast({
            title: '删除成功',
            icon: 'success'
          })
          doQuery()
        })
      })

    } else { }
  })
}
// 角色修改 
function handleUpdate(row) {
  reset();
  isCreate.value = false;
  const roleId = row.id || ids.value;
  queryOne(roleId).then((response) => {
    form.value = response;
    form.value.roleSort = Number(form.value.roleSort);
    form.value.deptId = response.deptId == undefined ? "" : response.deptId.toString();
    openModal();
    checkedKeys.value = [];
    checkedKeys.value = response.permissions;
    title.value = "修改角色";
  });
}
// 状态修改
function handleStatusChange(row) {
  let text = row.status === 0 ? "停用" : "启用";
  const data = row;
  $.showModal({
    title: '确认提醒',
    type: 'warning',
    content: `确认要"${text}"${row.roleName}"角色吗`,
    cancelText: '取消'
  }).then(r => {
    if (r.confirm) {
      updateOne(data).then(res => {
        $.showToast({
          title: `${text}成功`,
          icon: 'success'
        })
        doQuery()
      })
    } else {
      row.status = row.status === 0 ? 1 : 0;
    }
  })
}
// 查
function doQuery() {
  loading.value = true;
  queryList(queryParams.value).then((response) => {
    tableData.value = response.content;
    total.value = response.totalElements;
    loading.value = false;
  });
}
// 选中部门
function deptConfirm(e) {
  queryParams.value.deptId = e;
  handleQuery();
}
function openModal() {
  modalRef.value.openModal();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  doQuery();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.deptId = undefined;
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 分配用户 */
function handleAuthUser(row) {
  selectedRole.value = row;
  userGrantRef.value.openModal();
}
/**
* 构建选择树
* @param {*} arr
*/
function buildResTree(arr) {
  return arr;
}
/** 查询菜单树结构 */
function getResTree() {
  return new Promise(function (resolve, reject) {
    resTree().then((response) => {
      resOptions.value = buildResTree(response);
      resolve(resOptions.value);
    });
  });
}
/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    deptId: undefined,
    id: undefined,
    permissions: [],
    roleDescription: undefined,
    roleKey: undefined,
    roleName: undefined,
    roleSort: 0,
    status: 1,
  };
  proxy.resetForm("formRef");
}
// 提交
function submitTypeForm() {
  if (isCreate.value) {
    createOne(form.value).then((res) => {
      $.showToast({
        title: "创建成功",
        icon: "success",
      });
      doQuery()
      modalRef.value.closeModal();
    });
  } else {
    updateOne(form.value).then((res) => {
      $.showToast({
        title: "更新成功",
        icon: "success",
      });
      doQuery();
      modalRef.value.closeModal();
    });
  }
}
doQuery()
getResTree();
</script>